<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="改动类型" prop="alterType">
        <el-input
          v-model="queryParams.alterType"
          placeholder="请选择改动类型"
          clearable
          class="!w-220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="dictEnableStatus">
        <el-select
          v-model="queryParams.dictEnableStatus"
          placeholder="请选择状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creatorName">
        <el-input
          v-model="queryParams.creatorName"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="time">
        <el-date-picker
          v-model="time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
        
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="btnWrap">
      <div>
        <el-button
          type="primary"
          @click="openImport"
          v-hasPermi="['config:drawing-alter-type:import']"
        >
          数据导入
        </el-button>
        <el-button
          type="primary"
          @click="handleExport"
          v-hasPermi="['config:drawing-alter-type:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['config:drawing-alter-type:create']"
        >
          新增
        </el-button>
      </div>
      <div>
        <el-button
          type="primary"
          @click="openTableTitleSet"
        >
          表头设置
        </el-button>
      </div>
    </div>
    <!-- 表单 -->
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length ? true : false"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      @register="register"
      border
      :tableHeight="tableHeight"
    >
      <template #action="{ row }">
        <el-button
          link
          type="primary"
          @click="openForm('update', row.id)"
          v-hasPermi="['config:drawing-alter-type:update']"
        >
          编辑
        </el-button>
        <el-button
          link
          type="danger"
          @click="handleDelete(row.id)"
          v-hasPermi="['config:drawing-alter-type:delete']"
        >
          删除
        </el-button>
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DrawingAlterTypeForm ref="formRef" @success="getList" />
  <!-- 表头设置 -->
  <table-width-set ref="tableTitleSet" @refresh="getTableTitle" />
  <!-- 数据导入 -->
  <CusUploadFile ref="cusUploadFile" @refresh="getList"/>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
</template>

<script setup lang="ts" name="DrawingAlterType">
import { getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import * as DrawingAlterTypeApi from '@/api/config/drawingAlterType'
import DrawingAlterTypeForm from './DrawingAlterTypeForm.vue'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
const code = 'DrawingAlterType'  //表头名
const tableHeight = ref(0)

const queryParams = reactive({
  pageNo: 1,
  creatorName: null,  //创建人
  createTime: undefined,
  remark: null,
  alterType: undefined,
  dictEnableStatus: undefined,  //状态
})
const time = ref([])
const queryFormRef = ref() // 搜索的表单

// tableObject：表格的属性对象，可获得分页大小、条数等属性
// tableMethods：表格的操作对象，可进行获得分页、删除记录等操作
const { tableObject, tableMethods } = useTable({
  getListApi: DrawingAlterTypeApi.getDrawingAlterTypePage, // 分页接口
  defaultParams: queryParams
})

const parentRef = ref()
// 获取table组件
const register = (parent: any) => {
  parentRef.value = parent
}

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods

// 获取表头
const getTableTitle = async () => {
  const res = await DrawingAlterTypeApi.getDrawingAlterTypePage(queryParams)
  res.labels.push({
    field: 'action',
    label: '操作',
    align: 'left',
    headerAlign: 'left',
    width: 110
  })
  const { allSchemas } = useCrudSchemas(res.labels)
  tableTitleList.value = allSchemas.tableColumns
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitleList.value, code)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  queryParams.createTime = JSON.parse(JSON.stringify(time.value)).join(',')
  setSearchParams(queryParams)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  time.value = []
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DrawingAlterTypeApi.deleteDrawingAlterType(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 数据导入
const cusUploadFile = ref()
const openImport = () => {
  cusUploadFile.value.open('/config/drawing-alter-type/get-import-template', '/config/drawing-alter-type/import')
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 下载
const downloadFun = async () => {
  const val = exportRef.value.params
  const params = {
    fileName: val.name,
    ids: ''
  }
  if (val.range === 'all') {
    params.ids = ''
  } else {
    parentRef.value.selections.map((item) => {
      params.ids = (item as any).id + ',' + params.ids
    })
  }
  const data = await DrawingAlterTypeApi.exportDrawingAlterType(params)
  download.excel(data, val.name)
  parentRef.value.clearTableSelect()
}

/** 初始化 **/
onMounted(async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  getList()
  getTableTitle()
})
</script>
<style lang="scss" scoped>
.btnWrap {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
